package controller

import (
	bc "Agricultural/application/blockchain"
	"Agricultural/application/lib"
	"Agricultural/application/util"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// 公司录入一个资产
func CreateAssets(ctx *gin.Context)  {
	// 解析结构体
	req := new(lib.Assets)
	if err := ctx.ShouldBind(req); err != nil {
		_ = ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}
	req.Id = util.Krand(11, 0)
	req.PurchaseDate = time.Now()
	aa, _ := time.ParseDuration("24h")
	req.OverdueDate = time.Now().Add(60 * aa)
	marshal, _ := json.Marshal(req)
	resp, err := bc.ChannelExecute("createAssets", [][]byte{
		marshal,
		[]byte(req.Subjection),
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, resp)
}

// 公司修改资产
func UpdateAssets(ctx *gin.Context)  {
	companyId := ctx.Query("companyId")
	// 解析结构体
	req := new(lib.Assets)
	if err := ctx.ShouldBind(req); err != nil {
		_ = ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}
	marshal, _ := json.Marshal(req)
	resp, err := bc.ChannelExecute("updateAssets", [][]byte{
		marshal,
		[]byte(companyId),
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, resp)
}

// 公司删除资产
func DelAssets(ctx *gin.Context)  {
	companyId := ctx.Query("companyId")
	assetsId := ctx.Query("assetsId")
	resp, err := bc.ChannelExecute("delAssets", [][]byte{
		[]byte(assetsId),
		[]byte(companyId),
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, resp)
}

// 查询资产
func QueryAssets(ctx *gin.Context)  {
	companyId := ctx.Query("companyId")
	assetsId := ctx.Query("assetsId")
	resp, err := bc.ChannelExecute("queryAssets", [][]byte{
		[]byte(assetsId),
		[]byte(companyId),
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.String(http.StatusOK, bytes.NewBuffer(resp.Payload).String())
}